package com.chungkui.check.expression;


import com.chungkui.check.core.Constants;
import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.handler.insidecheck.InsideType;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public abstract class NumberMinMaxExpression extends BaseMinMaxExpression {
    private final Logger log = LoggerFactory.getLogger(NumberMinMaxExpression.class);

    public abstract Comparable getComparable(String v);

    @Override
    public CheckResult match(Map<String, Object> params) {
        String val = MapUtils.getString(params, this.param);
        if (this.require != null && this.require && StringUtils.isBlank(val)) {
            return CheckResult.fail(this.code, this.param, MapUtils.getString(this.msg, Constants.NULL, normalMsg), val);
        }
        try {
            if (StringUtils.isNotEmpty(val)) {
                Comparable v = getComparable(val.trim());
                return super.checkMinMax(min, max, v);
            }
        } catch (Exception e) {
            log.info("match fail", e);
            String msg = MapUtils.getString(this.msg, Constants.FAIL, normalMsg);
            return CheckResult.fail(this.code, this.param, StringUtils.isEmpty(msg) ? Constants.NUMBER_FAIL_MSG : msg, val);
        }
        return CheckResult.success();
    }

    @Override
    public InsideType getInsideType() {
        return InsideType.NO_INSISE;
    }
}
